
import Taro from '@tarojs/taro';
import { MaterialIcons } from 'taro-icons';
import React, { useEffect, useState, useRef, useCallback } from 'react';
import { View, Text, ScrollView, Button, Block } from '@tarojs/components';


import ScoreStar from '../../components/scoreStar';
import { getBaseDetailApi } from '../../api/baseApi';
import { userLoginLimit } from '../../contexts/store';
import LicenseTags from '../../components/LicenseTags';
import DataErrorView from '../../components/dataError';
import EmptyContent from '../../components/emptyContent';
import { useAppContext } from '../../contexts/AppContext';
import DataLoadingView from '../../components/dataLoading';
import { UserGenderImage } from '../../components/userGender';
import { UserAvatarImage } from '../../components/userAvatar';
import type { CoachItem, HotCoachItem } from '../../types/coach';
import { calculateGeoDistance } from "../../utils/coordTransform";
import type { CityBaseData, CityBaseItem } from '../../types/cityBase';
import { CityBaseImage } from '../../components/basePage/cityBaseImage';
import { getCoachesByBaseIdApi, getHotCoachesByBaseIdApi } from '../../api/coachApi';

import './index.scss';


/**
 * 基地详情页面组件
 * 展示基地的详细信息，包括基本信息、执照、交通等内容以及师资团队
 */
const BaseDetailPage: React.FC = () => {
  const { selectedCityBaseData, setSelectedCityBaseData, userLocation } = useAppContext();
  const [baseDetail, setBaseDetail] = useState<CityBaseData | null>(null);
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [error, setError] = useState<string | null>(null);
  const [hasMore, setHasMore] = useState<boolean>(true);
  const [totalItems, setTotalItems] = useState<number>(0);
  const [coaches, setCoaches] = useState<CoachItem[]>([]);
  const [currentPage, setCurrentPage] = useState<number>(1);
  const [loadingMore, setLoadingMore] = useState<boolean>(false);
  const [hotCoaches, setHotCoaches] = useState<HotCoachItem[]>([]);
  const [userDistance, setUserDistance] = useState<string>('公里');
  const [isBusinessOpen, setIsBusinessOpen] = useState<boolean>(false);

  const isInitialized = useRef(false);
  // 控制基地信息的显示/隐藏
  const [isBaseInfoVisible, setIsBaseInfoVisible] = useState<boolean>(true);
  // 记录上一次滚动位置，用于判断滑动方向
  const [lastScrollTop, setLastScrollTop] = useState<number>(0);

  const getBaseIdFromParams = () => {
    const params = Taro.getCurrentInstance().router?.params;
    return params?.id ? Number(params.id) : null;
  };

  const baseId = getBaseIdFromParams();

  /**
   * 获取教练列表数据
   * @param page - 页码
   * @param isLoadMore - 是否为加载更多操作
   */
  const fetchCoachesData = useCallback(async (page: number = 1, isLoadMore: boolean = false) => {
    const pageSize = 20;
    if (!baseId) return;
    if (!isLoadMore) {
      setIsLoading(true);
      // Taro.showLoading({ title: '加载中...' });
    }
    else setLoadingMore(true);
    try {
      const response = await getCoachesByBaseIdApi(baseId, page, pageSize);
      if (response.code === 200) {
        const newCoaches = response.data || [] as CoachItem[];
        const total = response.total || 0;
        setCoaches(prev => {
          const updatedCoaches = isLoadMore ? [...prev, ...(Array.isArray(newCoaches) ? newCoaches : [])] : (Array.isArray(newCoaches) ? newCoaches : []);
          return updatedCoaches;
        });
        setHasMore(response.has_more || false);
        setTotalItems(total);
      } else {
        if (!isLoadMore) {
          setError('获取教练数据失败，请稍后重试');
        }
      }
    } catch (err) {
      console.error('Failed to fetch coaches:', err);
      if (!isLoadMore) {
        setError('获取教练数据失败，请稍后重试');
      }
    } finally {
      if (!isLoadMore) setIsLoading(false);
      else setLoadingMore(false);
    }
  }, [baseId, setCoaches, setTotalItems, setHasMore, setError, setIsLoading, setLoadingMore]);

  // 加载热门教练数据
  const getHotCoachData = async () => {
    if (!baseId) return;
    try {
      const hotCoachResponse = await getHotCoachesByBaseIdApi(baseId);
      if (hotCoachResponse.code === 200 && hotCoachResponse.data && hotCoachResponse.data) {
        setHotCoaches(hotCoachResponse.data || []);
      }
    } catch (error) {
      console.error('Failed to fetch hot coaches:', error);
    }
  };

  // 加载基地详情数据
  const loadBaseDetail = async () => {
    setIsLoading(true);
    setError(null);
    try {
      // 优先使用全局状态中的数据，如果没有则从API获取
      if (selectedCityBaseData && selectedCityBaseData.base && 
          (!baseId || selectedCityBaseData.base.id === baseId)) {
        setBaseDetail(selectedCityBaseData);
        handleUserDistance(selectedCityBaseData.base);
      } else if (baseId) {
        const response = await getBaseDetailApi(baseId);
        if (response.code === 200 && response.data) {
          setBaseDetail(response.data);
          setSelectedCityBaseData(response.data);
          handleUserDistance(response.data.base);
        } else {
          setError('获取基地详情失败');
        }
      } else {
        setError('无法获取基地ID');
      }
    } catch (err) {
      setError('网络异常，请重试');
      console.error('Failed to load base detail:', err);
    } finally {
      setIsLoading(false);
    }
  };

  // 加载更多教练数据 - 修改为异步函数以处理Promise
  const loadMoreData = async () => {
    console.log('loadMoreData');
    if (!loadingMore && hasMore) {
      try {
        const nextPage = currentPage + 1;
        setCurrentPage(nextPage);
        fetchCoachesData(nextPage, true);
      } catch (error) {
        console.error('加载更多数据时出错:', error);
        // 即使获取视口中间元素失败，也继续加载数据
        const nextPage = currentPage + 1;
        setCurrentPage(nextPage);
        fetchCoachesData(nextPage, true);
      }
    }
  };

  const handleUserDistance = (base: CityBaseItem) => {
    const lat = base.latitude;
    const lng = base.longitude;
    if (userLocation && lat && lng) {
      const { longitude, latitude } = userLocation;
      const userDistance: any = calculateGeoDistance(longitude, latitude, lng, lat);
      console.log("用户距离:", userDistance)
      setUserDistance(`${userDistance.distance}${userDistance.unit}`);
    }
  }

  // 检查当前是否在营业时间内(9:00-18:00)
  const checkBusinessStatus = () => {
    const now = new Date();
    const currentHour = now.getHours();
    // 判断当前时间是否在9:00-18:00之间
    const isOpen = currentHour >= 9 && currentHour < 18;
    setIsBusinessOpen(isOpen);
  };

  // 组件挂载时加载数据
  useEffect(() => {
    if (!userLoginLimit('查看基地详情，需要登录服务')) return;
    if (!isInitialized.current) {
      loadBaseDetail();
      checkBusinessStatus();
      isInitialized.current = true;
    }
  }, []);

  // 当基地详情加载完成后，获取教练数据
  useEffect(() => {
    const fetchData = async () => {
      if (baseId) {
        await fetchCoachesData();
        await getHotCoachData();
      }
    }
    fetchData();
  }, [baseId]);

  const refreshData = async () => {
    // setRefreshStatus(true);
    await fetchCoachesData();
    await getHotCoachData();
    // Taro.stopPullDownRefresh();
    // setRefreshStatus(false);
  }

  // 处理查看教练详情
  const handleViewCoachDetail = (coachId: number) => {
    const baseId = getBaseIdFromParams();
    if (baseId) {
      Taro.navigateTo({
        url: `/pages/coach-detail/index?coachId=${coachId}&baseId=${baseId}`
      });
    }
  };

  if (isLoading) {
    return (
      <DataLoadingView />
    );
  }

  if (error) {
    return (
      <DataErrorView 
        title="获取基地详情失败"
        content={error}
        buttonText="出错了，请重试"
        onClickFunc={loadBaseDetail}
      />
    );
  }

  if (!baseDetail?.base) {
    return (
      <EmptyContent title='未找到基地信息'/>
    );
  }

  const openBaseMap = () => {
    const { base } = baseDetail;
    if (base.longitude && base.latitude) {
      Taro.openLocation({
        latitude: base.latitude,
        longitude: base.longitude,
        scale: 18
      });
    }else{
      Taro.showToast({
        title: '基地位置信息缺失,无法打开地图',
        icon: 'none'
      });
    }
  }

  // 处理滚动事件，控制基地信息的显示/隐藏
  const handleScroll = (e: any) => {
    const scrollTop = e.detail.scrollTop;
    
    // 当向上滑动且滚动距离大于50时，隐藏基地信息
    if (scrollTop > lastScrollTop && scrollTop > 50) {
      setIsBaseInfoVisible(false);
    }
    // 当向下滑动到顶部时，显示基地信息
    else if (scrollTop <= 10) {
      setIsBaseInfoVisible(true);
    }
    
    setLastScrollTop(scrollTop);
  }

  return (
    <View>
      {/* 基地头部信息 - 条件显示 */}
      <View className={`base-header ${isBaseInfoVisible ? '' : 'hidden'}`}>
        <CityBaseImage cityBase={baseDetail.base}/>
        {/* AR看场地按钮 */}
        <View className="base-ar-button">
          <Text className="base-ar-text text-lg">AR看场地 →</Text>
        </View>
      </View>

      {/* 基地基本信息 - 条件显示 */}
      <View className={`base-basic-info ${isBaseInfoVisible ? '' : 'hidden'}`}>
        <View className="base-info-item">
          <Text className="base-name text-lg">{baseDetail.base.name}</Text>
          <Text className="base-type text-md">{baseDetail.base.baseType || '训练基地'}</Text>
          <View className="base-info-runtime text-md">
            <Text>营业时间:</Text>
            <Text>9:00-18:00</Text>
            <View className="base-business-status">
              <Text className={`base-business-text text-lg ${isBusinessOpen ? 'open' : 'closed'}`}>
                {isBusinessOpen ? '营业中' : '休息中'}
              </Text>
            </View>
          </View>
        </View>
        <Text className="base-description text-base">{baseDetail.base.description || ''}</Text>
        <View className="base-info-item">
          <MaterialIcons name="place" color="#7cb305" size={24} />
          <Text className="base-info-value text-md">{baseDetail.base.address}</Text>
        </View>
        <View className="base-info-item">
            <View className="base-traffic-info">
              <MaterialIcons name="directions-car" color="#ff3141" size={24}/>
              <Text className="base-info-value text-md">距您约 <Text className="base-info-important">{userDistance}</Text></Text>
            </View>
            <Button className="base-navigate-btn text-md" onClick={openBaseMap}>导航</Button>
        </View>

        <View className="base-info-item text-sm">
          <MaterialIcons name="motorcycle" color="#1890ff" size={24}/>
          <LicenseTags className='base-info-license' licenseItems={baseDetail.baseLicense || []} />
        </View>
      </View>

      {/* 师资团队区域 */}
      <View className="base-coaches-section">
        <View className="base-coaches-header">
          <View className="base-coaches-title-container">
            <Text className="base-coaches-title text-lg">师资团队</Text>
          </View>

          <Text className="base-coaches-count text-md">共{totalItems}位教练</Text>
          <View onClick={refreshData}>
            <Text className="blue-color text-md">刷新</Text>
          </View>
        </View>

        <ScrollView 
          scrollY 
          lowerThreshold={200} 
          scrollWithAnimation
          onScrollToLower={loadMoreData}
          onScroll={handleScroll}
          style={{height: 1200}}
        >
          {isLoading && coaches.length === 0 ? (
            <DataLoadingView />
          ) : coaches.length === 0 ? (
            <EmptyContent title='暂无教练数据'/>
          ) : (
            <View className="base-coaches-list">
              {/* 热门教练区域 - 单行独列展示 */}
              {hotCoaches.length > 0 && (
                <View className="hot-coaches-section">
                  <Block>
                    {coaches.map((coach) => {
                      const hotCoach = hotCoaches.find(hc => hc.id === coach.id);
                      if (hotCoach) {
                        return (
                          <View 
                            key={coach.id} 
                            className="base-coach-item base-gold-coach-item hot-coach-full-width" 
                            onClick={() => handleViewCoachDetail(coach.id)}
                          >
                            {/* 左侧头像部分 */}
                            <View className="hot-coach-avatar-section">
                              <View className="base-hot-coach-avatar-container">
                                <UserAvatarImage
                                  user_id={coach.id}
                                  user_name={coach.username}
                                  avatar={coach.avatar} 
                                />
                              </View>
                            </View>
                            
                            {/* 中间个人信息部分 */}
                            <View className="hot-coach-info-section">
                              <View className="base-coach-info">
                                <View className="base-coach-name-row">
                                  <Text className="base-coach-name text-lg">{coach.username}</Text>
                                  <UserGenderImage gender={coach.gender || ''} />
                                </View>
                                <ScoreStar score={coach.score || 5} size={10}/>
                                <View className="base-coach-tags-row">
                                  <Text className="purple-tag text-base base-coach-tag-item">{coach.age ? `${coach.age}岁` : ''}</Text>
                                  <Text className="magenta-tag text-base base-coach-tag-item">{coach.experience_years ? `教龄${coach.experience_years}年` : ''}</Text>
                                  { coach.native? <View className="lime-tag text-base base-coach-tag-item">籍贯:{coach.native}</View> : <></>}
                                  {coach.licenses && (
                                    <LicenseTags licenseItems={coach.licenses || []}/>
                                  )}
                                </View>
                              </View>
                            </View>
                            
                            {/* 右侧月度报名数据部分 */}
                            {hotCoach && (
                              <View className="hot-coach-stats-section">
                                <View className="base-coach-stat-item">
                                  <Text className="base-coach-stat-label text-base">月度报名:</Text>
                                  <Text className="base-coach-stat-value text-md">{hotCoach.mouth_student || 0}人</Text>
                                </View>
                                <View className="base-coach-stat-item">
                                  <Text className="base-coach-stat-label text-base">年度报名:</Text>
                                  <Text className="base-coach-stat-value text-md">{hotCoach.year_student || 0}人</Text>
                                </View>
                              </View>
                            )}
                          </View>
                        );
                      }
                      return null;
                    }).filter(Boolean)}
                  </Block>
                </View>
              )}
              
              {/* 普通教练区域 - 一行两列展示 */}
              {coaches.filter(coach => !hotCoaches.find(hc => hc.id === coach.id)).length > 0 && (
                <View className="normal-coaches-section">
                  <View className="normal-coaches-grid">
                    <Block>
                      {coaches.map((coach) => {
                        const isHotCoach = hotCoaches.find(hc => hc.id === coach.id);
                        if (!isHotCoach) {
                          return (
                            <View 
                              key={coach.id} 
                              className="base-coach-item normal-coach-half-width" 
                              onClick={() => handleViewCoachDetail(coach.id)}
                            >
                              <View className="base-coach-avatar-container">
                                <UserAvatarImage
                                  user_id={coach.id}
                                  user_name={coach.username}
                                  avatar={coach.avatar} 
                                />
                              </View>
                              <ScoreStar score={coach.score || 5} size={10}/>
                              <View className="base-coach-info">
                                <View className="base-coach-name-row">
                                  <Text className="base-coach-name text-lg">{coach.username}</Text>
                                  <UserGenderImage gender={coach.gender || ''} />
                                </View>
                                <View className="base-coach-tags-row">
                                  <Text className="purple-tag text-base base-coach-tag-item">{coach.age ? `${coach.age}岁` : ''}</Text>
                                  <Text className="magenta-tag text-base base-coach-tag-item">{coach.experience_years ? `教龄${coach.experience_years}年` : ''}</Text>
                                  { coach.native? <View className="lime-tag text-base base-coach-tag-item">籍贯:{coach.native}</View> : <></>}
                                  {coach.licenses && (
                                    <LicenseTags licenseItems={coach.licenses || []}/>
                                  )}
                                </View>
                              </View>
                            </View>
                          );
                        }
                        return null;
                      }).filter(Boolean)}
                    </Block>
                  </View>
                </View>
              )}
            </View>
          )}
          
          {/* 加载更多提示 */}
          {hasMore && (
            <View className="base-loading-more" onClick={loadMoreData}>
              <Text className="base-loading-text">点击加载更多...</Text>
            </View>
          )}
          
          {/* 没有更多数据提示 */}
          {!hasMore && coaches.length > 0 && (
            <View className="base-no-more">
              <Text className="base-no-more-text">我也是有底线的哦~</Text>
            </View>
          )}
        </ScrollView>

      </View>
    </View>
  );
};

export default BaseDetailPage;